package org.dizem.intellipainter.component.shape;

import org.dizem.intellipainter.model.ShapeType;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

/**
 * User: dizem@126.com
 * Time: 12-2-18 下午6:54
 */
public class ShapeChooser extends JPanel {
	private static final Font font = new Font("微软雅黑", Font.PLAIN, 13);
	private final ShapeSelectCallback callback;
	private static final Dimension SIZE = new Dimension(120, 100);

	public ShapeChooser(ShapeSelectCallback callback) {
		this.callback = callback;
		setLayout(new BorderLayout());
		setPreferredSize(SIZE);
		setMaximumSize(SIZE);
		setMinimumSize(SIZE);
		add(createCenter(), BorderLayout.CENTER);
		add(createSouth(), BorderLayout.SOUTH);
	}


	private JPanel createCenter() {
		JPanel center = new JPanel(new FlowLayout());
		center.add(getToolPanel());
		return center;
	}

	private JLabel createSouth() {
		JLabel label = new JLabel("形状", JLabel.CENTER);
		label.setFont(font);
		label.setForeground(Color.GRAY);
		label.setPreferredSize(new Dimension(120, 20));
		return label;
	}

	private final java.util.List<ShapeButton> shapeButtons = new ArrayList<ShapeButton>();

	private JPanel getToolPanel() {
		JPanel panel = new JPanel(new GridLayout(2, 4, 3, 3));
		for (ShapeType shapeType : ShapeType.values()) {
			if (!shapeType.isEnable()) {
				continue;
			}
			final ShapeButton button = new ShapeButton(shapeType, callback);
			shapeButtons.add(button);
			button.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					button.setSelected(true);
					for (ShapeButton other : shapeButtons) {
						if (other != button) {
							other.setSelected(false);
						}
					}
				}
			});
			panel.add(button);
		}
		return panel;
	}

	public void setShapeType(ShapeType type) {
		for (ShapeButton button : shapeButtons) {
			if (button.getShapeType() == type) {
				button.doClick();
				break;
			}
		}
	}

}
